import { reqOrderAddress, reqOrderInfo, reqBuyNowGoods, reqSubmitOrder, reqPreBuyInfo } from '@/api/orderpay'
import { formatTime } from '@/utils/formatTime'
import Schema from 'async-validator'
const app = getApp()
Page({
  data: {
    buyName: '', // 订购人姓名
    buyPhone: '', // 订购人手机号
    deliveryDate: '', // 期望送达日期
    blessing: '', // 祝福语
    show: false, // 期望送达日期弹框
    orderAddress: {}, //收货地址
    orderInfo: {}, //订单信息
    minDate: new Date().getTime(),
    currentDate: new Date().getTime()
  },

  // 获取地址信息
  async getOrderAddress() {
    const addressId = app.globalData.address.id
    if (addressId) {
      this.setData({
        orderAddress: app.globalData.address
      })
      return
    }
    const { data } = await reqOrderAddress()
    // console.log(res)
    this.setData({
      orderAddress: data
    })
  },

  // 订单详情
  async getOrderInfo() {
    const { goodsId, blessing } = this.data
    const { data: orderInfo } = goodsId ? await reqBuyNowGoods({ goodsId, blessing }) : await reqOrderInfo()
    const orderGoods = orderInfo.cartVoList.find((item) => item.blessing !== '')
    this.setData({
      orderInfo,
      blessing: !orderGoods ? '' : orderGoods.blessing
    })
  },

  // 选择期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true
    })
  },

  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    // console.log(event.detail)
    const timeRes = formatTime(new Date(event.detail))
    // console.log(timeRes)
    this.setData({
      show: false,
      deliveryDate: timeRes
    })
  },

  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelTimePicker() {
    this.setData({
      show: false,
      minDate: new Date().getTime(),
      currentDate: new Date().getTime()
    })
  },

  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/modules/settingModule/modules/settingModule/pages/address/list/index'
    })
  },
  // 提交订单
  async submiOrder() {
    const { buyName, buyPhone, deliveryDate, blessing, orderAddress, orderInfo } = this.data
    const params = {
      buyName,
      buyPhone,
      cartList: orderInfo.cartVoList,
      deliveryDate,
      remarks: blessing,
      userAddressId: orderAddress.id
    }
    const { valid } = await this.validatePerson(params)
    if (!valid) return
    // console.log(res)
    const res = await reqSubmitOrder(params)
    if (res.code) {
      this.orderNo = res.data
      // 预支付
      this.advancePay()
    }
  },

  // 验证表单
  validatePerson(params) {
    // 验证姓名，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'

    // 验证手机号，是否符合中国大陆手机号码的格式
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rules = {
      userAddressId: [{ required: true, message: '地址不能为空' }],
      buyName: [
        { pattern: nameRegExp, message: '请输入正确订购人姓名' },
        { required: true, message: '订购人姓名不能为空' }
      ],
      buyPhone: [
        { required: true, message: '订购人手机号码不能为空' },
        { pattern: phoneReg, message: '订购人手机号码错误' }
      ],
      deliveryDate: [{ required: true, message: '送达日期不能为空' }]
    }
    const validator = new Schema(rules)
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          wx.toast({
            title: errors[0].message
          })
          resolve({ valid: false })
        } else {
          resolve({ valid: true })
        }
      })
    })
  },

  // 预支付
  async advancePay() {
    const payParams = await reqPreBuyInfo(this.orderNo)
    console.log(payParams)
    if (payParams.code === 200) {
      wx.navigateTo({
        url: '/modules/orderPayModule/pages/order/list/list'
      })
    }
    // try {
    //   const payParams = await reqPreBuyInfo(this.orderNo)
    //   // const { nonceStr, package, paySign, timeStamp } = payParams.data
    //   // console.log(nonceStr)
    //   if (payParams.code === 200) {
    //     console.log(payParams.data)
    //     wx.navigateTo({
    //       url: 'modules/orderPayModule/pages/order/list/list'
    //     })
    //     const payInfo = await wx.requestPayment(payParams.data)
    //     console.log(payInfo)
    //   }
    // } catch (error) {
    //   wx.toast({
    //     tetle: '支付失败！',
    //     icon: 'error'
    //   })
    // }
  },

  onShow() {
    this.getOrderAddress()
    this.getOrderInfo()
  },
  onUpload() {
    app.globalData.address = {}
  },
  onLoad(option) {
    this.setData({
      ...option
    })
    // console.log(option)
  }
})
